package com.pingan.haofang.searchcloud.batch.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

/**
 * 批处理任务bean注册器
 * 
 * @author LUYI374
 * @date 2017年3月8日
 * @since 1.0.0
 */
@Component
public class BatchHandlerBeanPostProcessor implements BeanPostProcessor {

    private static final String BASE_SCAN_PACKAGE = "com.pingan.haofang.searchcloud.batch";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!bean.getClass().getName().startsWith(BASE_SCAN_PACKAGE)) {
            return bean;
        }
        Batch config = AnnotationUtils.findAnnotation(bean.getClass(), Batch.class);
        if (config != null) {
            BatchRunInstance instance = new BatchRunInstance();
            instance.setConfig(config);
            instance.setRunner(bean);
            BatchRunnerFactory.addRunner(config.value(), instance);
        }
        return bean;
    }
}
